//
//  HeadNameView.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 14-6-5.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "HeadNameViewPanel.h"

#define BtnBorderMargin      5

@class HeadNameView;

@protocol HeadNameViewDelegate <NSObject>

-(void)headNameView:(HeadNameView*)headNameView clickInDeleteStatus:(NSString*)szTag;

-(void)headNameView:(HeadNameView*)headNameView click:(NSString*)szTag;

@end

@interface HeadNameView : UIView<UIViewExtendDelegate>

@property(nonatomic,strong) UIImage* headImage;
@property(nonatomic,strong) NSString* name;

@property(nonatomic,assign) BOOL showDeleteTag;

//固定，不出现删除标记
@property(nonatomic,assign) BOOL stick;

@property(nonatomic,weak) id<HeadNameViewDelegate> delegate;

@end

@interface HeadNameView ()<XUIButtonDelegate>
{
    XUIButton *_headView;
    XUIButton *_delTagBtn;
}
@end

@implementation HeadNameView

@synthesize szTag;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    _headView = [XUIButton buttonWithStyleType:XUIButtonStyleTypeTopHeadImage delegate:self];
    _headView.frame =CGRectMake(BtnBorderMargin, BtnBorderMargin, self.width - BtnBorderMargin*2, self.height - BtnBorderMargin*2);
    _headView.imageView.layer.cornerRadius = 5;
    _headView.imageView.clipsToBounds = YES;
    [self addSubview:_headView];
    
    _delTagBtn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeCenterImage delegate:self];
    _delTagBtn.frame = CGRectMake(0, 0, 30, 30);
    [_delTagBtn SetImage:[UIImage imageNamed:@"headviewpanel_deletetag.png"]];
    _delTagBtn.hidden = YES;
    _delTagBtn.center = CGPointMake(_headView.right, _headView.top);
    _delTagBtn.backgroundColor = [UIColor clearColor];
//    [self addSubview:_delTagBtn];
    
    self.backgroundColor = [UIColor clearColor];
    _headView.backgroundColor = [UIColor clearColor];
    
    return self;
}

-(void)setHeadImage:(UIImage *)headImage
{
    [_headView SetImage:headImage];
}

-(UIImage*)headImage
{
    return nil;
}

-(void)setName:(NSString *)name
{
    [_headView SetTitle:name];
}

-(NSString*)name
{
    return [_headView GetTitle];
}

-(void)setShowDeleteTag:(BOOL)showDeleteTag
{
    if(showDeleteTag == NO)
       [_delTagBtn removeFromSuperview];
    else
    {
        CGPoint p = CGPointMake(_headView.right, _headView.top);
        p = [self convertPoint:p toView:self.superview];
        _delTagBtn.center = p;
        [self.superview addSubview:_delTagBtn];
    }
    
    _showDeleteTag = showDeleteTag;
    _delTagBtn.hidden = !showDeleteTag;
}

-(void)removeFromSuperview
{
    [_delTagBtn removeFromSuperview];
    [super removeFromSuperview];
}

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    if(_delTagBtn != nil)
    {
        CGPoint p = CGPointMake(_headView.right, _headView.top);
        p = [self convertPoint:p toView:self.superview];
        _delTagBtn.center = p;
    }
}

- (BOOL)handleTitleContentRectOfButton:(XUIButton *)btn
{
    if(_headView == btn)
        return YES;
    return NO;
}

- (BOOL)handleImageContentRectOfButton:(XUIButton *)btn
{
    if(_headView == btn)
        return YES;
    return NO;
}

- (CGRect)button:(XUIButton *)btn titleContentRect:(CGRect)rect
{
    return CGRectMake(0, btn.width + 5, btn.width, btn.height - btn.width -5);
}

- (CGRect)button:(XUIButton *)btn imageContentRect:(CGRect)rect
{
    return CGRectMake(0,0,btn.width,btn.width);
}

- (UIFont *)titleFontInCustomButtonEx:(XUIButton *)btn
{
    return [UIFont systemFontOfSize:12];
}

-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    if(_showDeleteTag == YES)
       [_delegate headNameView:self clickInDeleteStatus:self.szTag];
    else
        [_delegate headNameView:self click:self.szTag];
}

@end

#define HeadNameViewWidth       60
#define HeadNameViewHeight          80

@interface HeadNameViewPanel ()<HeadNameViewDelegate>
{
    NSMutableArray *_headViews;
    
    HeadNameView *_addHeadView;
    HeadNameView *_deleteHeadView;

    CGFloat _leftRightBorderMargin;
    
    CGFloat _topBottomBorderMarginl;
    
    __weak id<HeadNameViewPanelDelegate> _delegate;
}

@end

@implementation HeadNameViewPanel

-(id)initWithFrame:(CGRect)frame delegate:(id<HeadNameViewPanelDelegate>)delegate
{
    //必须是90
    frame.size.height = 90;
    self = [super initWithFrame:frame];
    
    _maxHeadName = NSIntegerMax;
    
    _headViews = [NSMutableArray new];
    
    _delegate = delegate;
    
    if([UIDevice is47InchScreen])
        _leftRightBorderMargin = 12;
    else if([UIDevice is55InchScreen])
        _leftRightBorderMargin = 18;
    else
        _leftRightBorderMargin = 15;
    
    _topBottomBorderMarginl = 5;
    
    [self addHeadNameViewWithImage:[UIImage imageNamed:@"headviewpanel_add.png"] name:@"添加" andTag:@"add"];
    [self addHeadNameViewWithImage:[UIImage imageNamed:@"headviewpanel_delete.png"] name:@"删除" andTag:@"delete"];
    
    _addHeadView = [_headViews objectAtIndex:0];
    _deleteHeadView = [_headViews objectAtIndex:1];
    
    self.showEditBtn = YES;
    
    return self;
}

-(void)setShowEditBtn:(BOOL)showEditBtn
{
    _showEditBtn = showEditBtn;
    _addHeadView.hidden = !showEditBtn;
    _deleteHeadView.hidden = !showEditBtn;
}

-(void)addHeadNameViewWithImage:(UIImage*)headImage name:(NSString*)name andTag:(NSString*)szTag
{
    HeadNameView *view = [[HeadNameView alloc]initWithFrame:CGRectMake(_leftRightBorderMargin, _topBottomBorderMarginl, HeadNameViewWidth, HeadNameViewHeight)];
    view.delegate = self;
    view.headImage = headImage;
    if(headImage == nil)
        view.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
    view.name = name;
    view.szTag = szTag;
    
    NSUInteger i = 0;
    if(_headViews.count == 0)
    {
        i=0;
    }
    else
    {
        for(NSInteger j = _headViews.count -1;j >= 0;j--)
        {
            HeadNameView *h = [_headViews objectAtIndex:j];
            if( h != _addHeadView && h!= _deleteHeadView)
            {
                i= j+1;
                break;
            }
        }
    }
    
    [_headViews insertObject:view atIndex:i];
    
    if(_headViews.count > 1)
    {
        if(i == 0)
            i++;
        for(NSUInteger n = i;n<_headViews.count;n++)
        {
            CGFloat xx = 0;
            CGFloat yy = 0;
            CGRect frame = ((HeadNameView *)[_headViews objectAtIndex:n -1]).frame;
            if(frame.origin.x + frame.size.width + _leftRightBorderMargin + frame.size.width  > self.width)
            {
                xx = _leftRightBorderMargin;
                yy = frame.origin.y +frame.size.height + _topBottomBorderMarginl;
            }
            else
            {
                xx = frame.origin.x + frame.size.width + _leftRightBorderMargin;
                yy = frame.origin.y;
            }
            ((HeadNameView *)[_headViews objectAtIndex:n]).origin = CGPointMake(xx, yy);
        }
    }
    
    [self addSubview:view];
    
    HeadNameView *last = nil;
    if(_headViews.count - 2 >= _maxHeadName)
    {
        
    }
    else if(self.showEditBtn == YES)
    {
        last = [_headViews objectAtIndex:_headViews.count-1];
    }
    else
    {
        if(_headViews.count <= 2)
            last = [_headViews objectAtIndex:0];
        else
            last = [_headViews objectAtIndex:_headViews.count - 3];
    }
    if(last.bottom + _topBottomBorderMarginl > self.height)
    {
        CGFloat oriHeight = self.height;
        self.height = last.bottom + _topBottomBorderMarginl;
        if(oriHeight != self.height)
            [_delegate headNameViewPanel:self resizeNewHeight:self.height];
    }
}

-(void)insertHeadNameViewAtIndex:(NSUInteger)index withImage:(UIImage*)headImage name:(NSString*)name andTag:(NSString*)szTag
{
    HeadNameView *view = [[HeadNameView alloc]initWithFrame:CGRectMake(_leftRightBorderMargin, _topBottomBorderMarginl, HeadNameViewWidth, HeadNameViewHeight)];
    view.delegate = self;
    view.headImage = headImage;
    if(headImage == nil)
        view.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
    view.name = name;
    view.szTag = szTag;
    
    [_headViews insertObject:view atIndex:index];
    
    NSUInteger i = index;
    if(_headViews.count>1)
    {
        if(i == 0)
            i++;
        for(NSUInteger n = i;n<_headViews.count;n++)
        {
            CGFloat xx = 0;
            CGFloat yy = 0;
            CGRect frame = ((HeadNameView *)[_headViews objectAtIndex:n -1]).frame;
            if(frame.origin.x + frame.size.width + _leftRightBorderMargin + frame.size.width  > self.width)
            {
                xx = _leftRightBorderMargin;
                yy = frame.origin.y +frame.size.height + _topBottomBorderMarginl;
            }
            else
            {
                xx = frame.origin.x + frame.size.width + _leftRightBorderMargin;
                yy = frame.origin.y;
            }
            ((HeadNameView *)[_headViews objectAtIndex:n]).origin = CGPointMake(xx, yy);
        }
    }
    
    [self addSubview:view];
    
    HeadNameView *last = nil;
    if(_headViews.count - 2 >= _maxHeadName)
    {
        _deleteHeadView.frame = _addHeadView.frame;
        _addHeadView.hidden = YES;
        last = _deleteHeadView;
    }
    else if(self.showEditBtn == YES)
    {
        last = [_headViews objectAtIndex:_headViews.count-1];
    }
    else
    {
        if(_headViews.count <= 2)
            last = [_headViews objectAtIndex:0];
        else
            last = [_headViews objectAtIndex:_headViews.count - 3];
    }
    
    if(last.bottom + _topBottomBorderMarginl > self.height)
    {
        CGFloat oriHeight = self.height;
        self.height = last.bottom + _topBottomBorderMarginl;
        if(oriHeight != self.height)
            [_delegate headNameViewPanel:self resizeNewHeight:self.height];
    }
}

-(void)removeHeadViewWithTag:(NSString*)szTag
{
    for(NSUInteger i=0;i<_headViews.count;i++)
    {
        HeadNameView *delHeadView = [_headViews objectAtIndex:i];
        if([delHeadView.szTag isEqualToString:szTag])
        {
            [delHeadView removeFromSuperview];
            
            CGRect preFrame = delHeadView.frame;
            for(NSUInteger j = i+1 ;j<_headViews.count;j++)
            {
                HeadNameView *v = [_headViews objectAtIndex:j];
                CGRect curFrame = v.frame;
                v.frame = preFrame;
                preFrame = curFrame;
            }
            
            [_headViews removeObject:delHeadView];
            
            HeadNameView *last = nil;
            if(_headViews.count + 1 >= _maxHeadName)
            {
                _addHeadView.hidden = NO;
                last = _deleteHeadView;
            }
            else if(self.showEditBtn == YES)
            {
                last = [_headViews objectAtIndex:_headViews.count-1];
            }
            else
            {
                if(_headViews.count <= 2)
                    last = [_headViews objectAtIndex:0];
                else
                    last = [_headViews objectAtIndex:_headViews.count - 3];
            }
            if(self.height >last.bottom + _topBottomBorderMarginl)
            {
                CGFloat oriHeight = self.height;
                self.height = last.bottom + _topBottomBorderMarginl;
                if(oriHeight != self.height)
                    [_delegate headNameViewPanel:self resizeNewHeight:self.height];
            }
            
            break;
        }
    }
}

-(void)reloadHeadNameViewWithBlock:(void(^)(void(^fun)(UIImage *headImage,NSString* name,NSString *szTag)))reloadHeadNameView
{
    NSArray *ar = [NSArray arrayWithArray:_headViews];
    for(HeadNameView *view in ar)
    {
        if(view.stick != YES && view != _addHeadView && view != _deleteHeadView)
        {
            [view removeFromSuperview];
            [_headViews removeObject:view];
        }
    }
    
    NSMutableArray *newHeadView = [NSMutableArray new];
    
    void(^f)(UIImage *headImage,NSString* name,NSString *szTag)=^(UIImage *headImage,NSString* name,NSString *szTag)
    {
        HeadNameView *view = [[HeadNameView alloc]initWithFrame:CGRectMake(_leftRightBorderMargin, _topBottomBorderMarginl, HeadNameViewWidth, HeadNameViewHeight)];
        view.delegate = self;
        view.headImage = headImage;
        if(headImage == nil)
            view.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
        view.name = name;
        view.szTag = szTag;
        
        [newHeadView addObject:view];
    };
    reloadHeadNameView(f);
    
    NSUInteger i = 0;
    
    for(NSUInteger j = 0;j < _headViews.count; j++ )
    {
        i = j;
        HeadNameView *v = _headViews[i];
        if(v.stick != YES)
        {
            break;
        }
    }
    
    for(HeadNameView *view in newHeadView)
    {
        [_headViews insertObject:view atIndex:i];
        
        [self insertSubview:view atIndex:i];
        
        i++;
    }
    
    ((HeadNameView*)[_headViews objectAtIndex:0]).origin = CGPointMake(_leftRightBorderMargin, _topBottomBorderMarginl);
    for(NSUInteger n = 1;n<_headViews.count;n++)
    {
        CGFloat xx = 0;
        CGFloat yy = 0;
        CGRect frame = ((HeadNameView *)[_headViews objectAtIndex:n -1]).frame;
        if(frame.origin.x + frame.size.width + _leftRightBorderMargin + frame.size.width  > self.width)
        {
            xx = _leftRightBorderMargin;
            yy = frame.origin.y +frame.size.height + _topBottomBorderMarginl;
        }
        else
        {
            xx = frame.origin.x + frame.size.width + _leftRightBorderMargin;
            yy = frame.origin.y;
        }
        ((HeadNameView *)[_headViews objectAtIndex:n]).origin = CGPointMake(xx, yy);
    }
    
    HeadNameView *last = nil;
    
    if(_headViews.count - 2 >= _maxHeadName)
    {
        _deleteHeadView.frame = _addHeadView.frame;
        _addHeadView.hidden = YES;
        last = _deleteHeadView;
    }
    else if(self.showEditBtn == YES)
    {
        last = [_headViews objectAtIndex:_headViews.count-1];
    }
    else
    {
        if(_headViews.count <= 2)
            last = [_headViews objectAtIndex:0];
        else
            last = [_headViews objectAtIndex:_headViews.count - 3];
    }
    
    if(last.bottom + _topBottomBorderMarginl != self.height)
    {
        CGFloat oriHeight = self.height;
        self.height = last.bottom + _topBottomBorderMarginl;
        if(oriHeight != self.height)
            [_delegate headNameViewPanel:self resizeNewHeight:self.height];
    }
}

-(void)refreshHeadImage:(UIImage*)headImage withTag:(NSString*)szTag
{
    for(HeadNameView *h in _headViews)
    {
        if([h.szTag isEqualToString:szTag])
        {
            h.headImage = headImage;
            break;
        }
    }
}

-(void)setStickHeadViewWithTag:(NSString*)szTag
{
    for(HeadNameView *h in _headViews)
    {
        if([h.szTag isEqualToString:szTag])
        {
            h.stick = YES;
            break;
        }
    }
}

-(void)headNameView:(HeadNameView *)headNameView clickInDeleteStatus:(NSString *)szTag
{
    for(NSUInteger i=0;i<_headViews.count;i++)
    {
        HeadNameView *delHeadView = [_headViews objectAtIndex:i];
        if([delHeadView.szTag isEqualToString:szTag])
        {
            [_delegate headNameViewPanel:self clickDeleteMaskBtn:szTag];
            break;
        }
    }
}

-(void)headNameView:(HeadNameView *)headNameView click:(NSString *)szTag
{
    if(headNameView == _addHeadView)
       [_delegate headNameViewPanel:self clickAddBtn:nil];
    else if(headNameView == _deleteHeadView)
    {
        for(HeadNameView *head in _headViews)
        {
            if(head.stick == NO && head != _addHeadView && head != _deleteHeadView)
            {
                head.showDeleteTag = ! head.showDeleteTag ;
            }
        }
    }
    else
    {
        for(HeadNameView *head in _headViews)
        {
            if(head.showDeleteTag == YES)
            {
                return;
            }
        }
        [_delegate headNameViewPanel:self clickNormalStateBtn:szTag];
    }
}

-(void)resetHeadViewDeleteTag
{
    for(HeadNameView *head in _headViews)
    {
        if(head.stick == NO && head != _addHeadView && head != _deleteHeadView)
        {
            head.showDeleteTag = NO ;
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for(HeadNameView *head in _headViews)
    {
        if(head.stick == NO && head != _addHeadView && head != _deleteHeadView)
        {
            head.showDeleteTag = NO ;
        }
    }
}

@end
